<?php
namespace app\admin\middleware;

use app\common\model\OperLogModel;
use think\facade\Log;
use app\common\model\auth\AdminModel;

class OperLogMiddleware
{
    public function handle($request, \Closure $next)
    {
        // 记录请求日志
        // Log::info('请求开始', ['url' => $request->url(), 'method' => $request->method()]);

        // 调用下一个中间件
        $response = $next($request);
        $this->log($request, $response);
        // 记录响应日志
        // Log::info('请求结束', ['status' => $response->getCode()]);

        return $response;
    }

    protected function log($request, $response)
    {
        $ip = get_client_ip();
        // 获取IP地址的地理位置
        $ip2region = new \Ip2Region();
        $ipLocation = $ip2region->simple($ip);
        $adminId = $request->admin_id;
        $account = AdminModel::where('id',$adminId)->value('account') ?? '未知';
        $logData = [
            'account' => $account, // 假设用户ID存储在Session中
            'router' => $request->baseUrl(),
            'method' => $request->method(),
            // 'request_data' => json_encode($request->param()),
            // 'response_data' => json_encode($response->getData()),
            'response_code' => $response->getCode(),
            'ip' => $ip,
            'ip_location' => $ipLocation,
            'created_at' => date('Y-m-d H:i:s')
        ];

        // 插入日志数据到数据库
        OperLogModel::create($logData);
    }
}